package com.example.testmvc.controller;

import com.example.testmvc.pojo.User;
import com.example.testmvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Cavan
 * @date 2023-06-01
 * @qq 2069543852
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //用户注册
    @RequestMapping("/register")
    public String register(User user){
        //注册用户
        try {
            userService.register(user);
        }catch (RuntimeException e){
            //出现异常，注册失败，重定向到注册页面
            e.printStackTrace();
            return "redirect:/register";
        }
        //没有出现异常，注册成功，重定向到登陆页面
        return "redirect:/login";
    }

    //用户登录
    @RequestMapping("/login")
    public String login(String id, String password, Model model){
        try {
            User user = userService.login(id, password);
            model.addAttribute("user", user);

        }catch (RuntimeException e){
            //登录失败
            e.printStackTrace();
            return "redirect:/login";
        }
        return "index";
    }

}
